package com.learning.assignment_1;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class GaleryActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listviewdemo);
		HorizontialListView listview = (HorizontialListView) findViewById(R.id.listview);
		getAllGaleryImage();
		listview.setAdapter(mAdapter);
	}
	
	private void getAllGaleryImage(){
		File dir = new File(Environment.getExternalStorageDirectory() + "/MyGallery");
		if(!dir.exists() || (!dir.isDirectory())) {
		    dir.mkdir();
		}
		        
		    File list[] = dir.listFiles();

		    for( int i=0; i< list.length; i++)
		    {	
		    	if (list[i].getName().toLowerCase().contains(".png") || list[i].getName().toLowerCase().contains(".jpeg")){
		    		String pathName = (Environment.getExternalStorageDirectory() + "/MyGallery/" + list[i].getName());
		    		Bitmap bitmap = BitmapFactory.decodeFile(pathName);
		    		dataObjects.add(bitmap);
		    	}
		    }
	}
	
	@Override
	protected void onDestroy (){
		super.onDestroy();
		for (Bitmap bm : dataObjects)
			bm.recycle();
		dataObjects.clear();
	} 
	private static ArrayList<Bitmap> dataObjects = new ArrayList<Bitmap>();

	private BaseAdapter mAdapter = new BaseAdapter() {

		@Override
		public int getCount() {
			return dataObjects.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View retval = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.listitem, null);
			ImageView iv = (ImageView) retval.findViewById(R.id.imageGalery);
			iv.setImageBitmap(dataObjects.get(position));
			return retval;
		}

	};
}
